package com.bc.trade.channel.ntlmh;

import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

import com.fs.common.util.FSString;

public class NtlmhUtil {
	

	private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	public static String MD5(String data) throws Exception  {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] signed = md5.digest(data.getBytes("UTF-8"));
		return bytesToHex(signed);
	}
	
	public static String signMD5(Map<String, String> map, String secretKey) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=").append(map.get("partner")).append('&')
			.append("banktype=").append(map.get("banktype")).append('&')
			.append("paymoney=").append(map.get("paymoney")).append('&')
			.append("ordernumber=").append(map.get("ordernumber")).append('&')
			.append("callbackurl=").append(map.get("callbackurl"))
			.append(secretKey);
		MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] signed = md5.digest(sb.toString().getBytes("UTF-8"));
        return bytesToHex(signed);
    }
	
	public static String bytesToHex(byte[] bytes) {
        // 一个byte为8位，可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a = 0;
        int index = 0;
        for(byte b : bytes) { // 使用除与取余进行转换
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }
            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }

        return new String(buf);
    }

	public static String signForDefray(TreeMap<String, String> params, String secretKey) throws Exception {
		String buff = FSString.convertMapToUrlParameter(params)+ "&key=" + secretKey;
		return MD5(buff);
	}

}
